package com.ip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ip.expception.ParamException;
import com.ip.mapper.UserInfoMapper;
import com.ip.pojo.model.UserInfoDO;
import com.ip.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserInfoMapper,UserInfoDO> implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public int saveUserInfo(String openid, String username, String headUrl) {
        if (StringUtils.isBlank(openid) || StringUtils.isBlank(username)) {
            throw new ParamException("save user info failed! param cannot is blank!");
        }
        LambdaQueryWrapper<UserInfoDO> queryWrapper = Wrappers.lambdaQuery(UserInfoDO.class);
        queryWrapper.eq(UserInfoDO::getOpenid,openid);
        queryWrapper.last("limit 1");
        UserInfoDO userInfo = this.getOne(queryWrapper);
        if (userInfo == null) {
            userInfo = new UserInfoDO();
            userInfo.setOpenid(openid);
            userInfo.setUsername(username);
            userInfo.setHeadImgUrl(headUrl);
            return userInfoMapper.insert(userInfo);
        } else {
            userInfo.setUsername(username);
            userInfo.setHeadImgUrl(headUrl);
            return userInfoMapper.updateById(userInfo);
        }
    }

    @Override
    public UserInfoDO queryByOpenid(String openid) {
        if (StringUtils.isBlank(openid)) {
            return null;
        }
        LambdaQueryWrapper<UserInfoDO> queryWrapper = Wrappers.lambdaQuery(UserInfoDO.class);
        queryWrapper.eq(UserInfoDO::getOpenid,openid);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }
}
